import axios from 'axios'
import config from '@/config.js'
import util from '@/util/util.js'
const URLWEBHTTP = config.URLWEBHTTP

/**
 * 封装的axios和ajax 一般用axios足够。如果有jsonp需求可以使用zport的ajax;
 */

export default async (apiurl = '', params = {}, type = 'GET', method = 'axios',id='') => {
    // console.log(params);
    type = type.toUpperCase();
    if (method == 'axios') {
        let Authorization = sessionStorage.getItem("Authorization");
        return new Promise((resolve, reject) => {
            axios({
                method: type,
                url:id == '' ? URLWEBHTTP + apiurl:URLWEBHTTP + apiurl+'/'+id,
                headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                    'Authorization':Authorization,
                },
                // withCredentials: true,
                data: ((type == 'POST') || (type ==  'PUT')) ? params : '',
                params: ((type == 'GET') || (type ==  'DELETE')) ? params : '',
                // timeout: appConfigs.timeout,
                /* 开启跨域cookie携带 */
                // credentials : true,
                // emulateHTTP: true,
                // emulateJSON:true
            }).then(res => {
                resolve(res);
                var authorization = res.headers.authorization;
                if (authorization){
                    sessionStorage.authorization = authorization;
                    // console.log(sessionStorage.authorization);
                }
                // let user = JSON.parse(window.localStorage.getItem('access-user'));
                //如果接口提示未登录，跳转登陆页面
                // if(res.data.message == '用户未登录'){
                //     window.location.href='/admin/#/login';
                // }
            }).catch(err => {
                //util.vueEvent.$emit('disloading')
                reject(err)
            })
        });
    } else if(method == 'export'){
        var location = '?';
        for (var i in params){
            location += `&${i}=${params[i]}`;
        }
        window.location.href = URLWEBHTTP + apiurl + location;
        // window.open(apiurl+location);
    } else {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: URLWEBHTTP + apiurl,
                dataType: 'jsonp',
                data: params,
                jsonp: 'callback',
                success: function(res) {
                    resolve(res)
                },
                error: function(res) {
                    reject(res)
                }
                // timeout: 50000
            })
        });
    }
}
